// 消息过滤逻辑

import type { Message } from './chat-types';

/**
 * 获取目标用户的所有可能ID（open_id、用户名、snowflake_id等）
 */
function getTargetUserIds(targetId: string): Set<string> {
  const ids = new Set<string>([targetId]);
  
  // 尝试从好友列表中查找所有可能的ID
  try {
    const friendsStr = localStorage.getItem('friends') || '[]';
    const friends = JSON.parse(friendsStr);
    
    const friend = friends.find((f: any) => {
      const friendData = f.user || f;
      return friendData.open_id === targetId || 
             friendData.name === targetId || 
             f.to_id === targetId ||
             (friendData.snowflake_id && String(friendData.snowflake_id) === targetId);
    });
    
    if (friend) {
      const friendData = friend.user || friend;
      if (friendData.open_id) ids.add(friendData.open_id);
      if (friendData.name) ids.add(friendData.name);
      if (friend.to_id) ids.add(friend.to_id);
      if (friendData.snowflake_id) ids.add(String(friendData.snowflake_id));
      if (friendData.id) ids.add(String(friendData.id));
    }
  } catch (e) {
    // 解析失败，忽略
  }
  
  return ids;
}

/**
 * 过滤消息，只返回属于当前查看目标的消息
 */
export function filterMessages(
  messages: Message[],
  targetId: string,
  targetType: 'User' | 'Group',
  currentUserId: string
): Message[] {
  if (!targetId) {
    return [];
  }

  const normalizeId = (id: string) => {
    return id.replace(/^group_/i, '').trim().toLowerCase();
  };

  // 获取目标用户的所有可能ID（用于单聊匹配）
  const targetUserIds = targetType === 'User' ? getTargetUserIds(targetId) : new Set<string>([targetId]);
  const normalizedTargetIds = new Set(Array.from(targetUserIds).map(id => normalizeId(id)));

  // 获取当前用户的所有可能ID
  const currentUserIds = new Set<string>([currentUserId]);
  try {
    const userStr = localStorage.getItem('user') || '{}';
    const user = JSON.parse(userStr);
    if (user.open_id) currentUserIds.add(user.open_id);
    if (user.name) currentUserIds.add(user.name);
    if (user.snowflake_id) currentUserIds.add(String(user.snowflake_id));
    if (user.id) currentUserIds.add(String(user.id));
  } catch (e) {
    // 解析失败，忽略
  }
  const normalizedCurrentUserIds = new Set(Array.from(currentUserIds).map(id => normalizeId(id)));

  const filtered = messages.filter(msg => {
    const msgToId = String(msg.to_user_id || '').trim();
    const msgFromId = String(msg.from_user_id || '').trim();
    const normalizedMsgToId = normalizeId(msgToId);
    const normalizedMsgFromId = normalizeId(msgFromId);
    const isReceived = msg.isReceived;

    // 判断消息是否属于当前查看的目标
    if (targetType === 'Group') {
      // 查看群组：只要 to_user_id 匹配当前群组ID，就显示（不管chat_type）
      // 这样可以显示从2人升级到3人之前的单聊消息
      const normalizedTargetId = normalizeId(targetId);
      const normalizedMsgToIdLower = normalizedMsgToId.toLowerCase();
      const normalizedTargetIdLower = normalizedTargetId.toLowerCase();
      
      // 多种匹配方式，确保能匹配到群组消息
      const matches = 
        normalizedMsgToIdLower === normalizedTargetIdLower ||
        msgToId === targetId ||
        msgToId.replace(/^group_/i, '').toLowerCase() === targetId.replace(/^group_/i, '').toLowerCase() ||
        msgToId === targetId.replace(/^group_/i, '') ||
        msgToId.replace(/^group_/i, '') === targetId ||
        msgToId.replace(/^group_/i, '').toLowerCase() === targetId.replace(/^group_/i, '').toLowerCase();

      if (!matches) {
        // 添加调试日志，帮助排查群组消息匹配问题
        if (import.meta.env.DEV && msg.chat_type === 2) {
          console.log('🔍 群组消息未匹配:', {
            message_id: msg.message_id,
            msg_to_user_id: msgToId,
            normalized_msg_to_id: normalizedMsgToId,
            target_id: targetId,
            normalized_target_id: normalizedTargetId,
            chat_type: msg.chat_type,
            isReceived: msg.isReceived,
          });
        }
        return false;
      }
      
      // 如果匹配成功，添加调试日志（仅在需要时输出，避免重复）
      // 注释掉频繁的日志输出，减少控制台噪音
      // if (import.meta.env.DEV && msg.chat_type === 2) {
      //   console.log('✅ 群组消息匹配成功:', {
      //     message_id: msg.message_id,
      //     msg_to_user_id: msgToId,
      //     target_id: targetId,
      //     chat_type: msg.chat_type,
      //   });
      // }
    } else {
      // 查看单聊：需要匹配目标用户的所有可能ID
      // 对于接收的消息，from_user_id 是对方，to_user_id 是当前用户
      // 对于发送的消息，from_user_id 是当前用户，to_user_id 是对方
      
      // 检查 from_user_id 是否匹配目标用户
      const isFromTarget = targetUserIds.has(msgFromId) || 
                          normalizedTargetIds.has(normalizedMsgFromId);
      
      // 检查 to_user_id 是否匹配目标用户
      const isToTarget = targetUserIds.has(msgToId) || 
                        normalizedTargetIds.has(normalizedMsgToId);
      
      // 检查 from_user_id 是否匹配当前用户
      const isFromCurrentUser = currentUserIds.has(msgFromId) || 
                                normalizedCurrentUserIds.has(normalizedMsgFromId);
      
      // 检查 to_user_id 是否匹配当前用户
      const isToCurrentUser = currentUserIds.has(msgToId) || 
                             normalizedCurrentUserIds.has(normalizedMsgToId);

      // 单聊消息：要么是发送给目标的，要么是从目标接收的
      const isSingleChatMessage = (isReceived && isFromTarget && isToCurrentUser) ||
                                 (!isReceived && isFromCurrentUser && isToTarget);

      if (!isSingleChatMessage) {
        // 检查是否是群组消息（不应该在单聊中显示）
        // 如果 to_user_id 在群组列表中，说明是群组消息，应该过滤掉
        try {
          const groupsStr = localStorage.getItem('groups') || '[]';
          const groups = JSON.parse(groupsStr);
          const isGroupMessage = groups.some((g: any) => {
            const group = g.group || g;
            const groupId = String(group.group_id || '');
            return normalizeId(groupId) === normalizedMsgToId || groupId === msgToId;
          });

          if (isGroupMessage) {
            // 这是群组消息，不应该在单聊中显示
            return false;
          }
        } catch (e) {
          // 解析失败，继续处理
        }

        // 如果既不是单聊消息，也不是明确的群组消息，过滤掉
        return false;
      }
    }

    // 如果通过了上面的过滤，说明消息属于当前查看的目标
    return true;
  });

  // 按时间戳排序
  const sorted = filtered.sort((a, b) => (a.timestamp_ms || a.timestamp) - (b.timestamp_ms || b.timestamp));

  // 添加调试日志
  if (import.meta.env.DEV) {
    if (filtered.length === 0 && messages.length > 0) {
      console.warn('⚠️ 消息过滤结果为空，但总消息数 > 0:', {
        targetId,
        targetType,
        currentUserId,
        totalMessages: messages.length,
        targetUserIds: Array.from(targetUserIds),
        normalizedTargetIds: Array.from(normalizedTargetIds),
        currentUserIds: Array.from(currentUserIds),
        normalizedCurrentUserIds: Array.from(normalizedCurrentUserIds),
        sampleMessages: messages.slice(0, 5).map(m => ({
          from_user_id: m.from_user_id,
          to_user_id: m.to_user_id,
          isReceived: m.isReceived,
          chat_type: m.chat_type,
          message_id: m.message_id,
        })),
      });
    } else if (filtered.length < messages.length) {
      console.log('📊 消息过滤统计:', {
        targetId,
        targetType,
        totalMessages: messages.length,
        filteredMessages: filtered.length,
        filteredOut: messages.length - filtered.length,
      });
    }
  }

  return sorted;
}

